<template>
  <fs-page>
    <template #header>
      <div class="title">
        机构管理
        <fs-icon icon="octicon:organization-24" :spin="true" />
      </div>
    </template>
    <n-grid class="mt-4" cols="1 s:1 m:1 l:3 xl:3 2xl:3" responsive="screen" :x-gap="12">
      <n-gi span="1">
        <n-card :segmented="{ content: true }" :bordered="false" size="small">
          <template #header>
            <n-space>
              <n-button type="info" ghost icon-placement="right" @click="openCreateDrawer">
                添加机构
                <template #icon>
                  <div class="flex items-center">
                    <n-icon size="14">
                      <FileAddTwotone />
                    </n-icon>
                  </div>
                </template>
              </n-button>
              <n-button type="info" ghost icon-placement="left" @click="packHandle">
                全部{{ expandedKeys.length ? '收起' : '展开' }}
                <template #icon>
                  <div class="flex items-center">
                    <n-icon size="14">
                      <AlignLeftOutlined />
                    </n-icon>
                  </div>
                </template>
              </n-button>
            </n-space>
          </template>
          <div class="w-full menu">
            <n-input type="input" v-model:value="pattern" placeholder="输入机构名称搜索">
              <template #suffix>
                <n-icon size="18" class="cursor-pointer">
                  <SearchOutlined />
                </n-icon>
              </template>
            </n-input>
            <div class="py-3 menu-list">
              <template v-if="loading">
                <div class="flex items-center justify-center py-4">
                  <n-spin size="medium" />
                </div>
              </template>
              <template v-else>
                <n-tree
                  block-line
                  cascade
                  checkable
                  default-expand-all
                  :show-irrelevant-nodes="false"
                  :virtual-scroll="true"
                  :pattern="pattern"
                  :data="treeData"
                  :defaultExpandedKeys="expandedKeys"
                  style="max-height: 650px; overflow: hidden"
                  @update:selected-keys="selectedTree"
                  @update:expanded-keys="onExpandedKeys"
                />
              </template>
            </div>
          </div>
        </n-card>
      </n-gi>
      <n-gi span="2">
        <n-card :segmented="{ content: true }" :bordered="false" size="small">
          <template #header>
            <n-space>
              <n-icon size="18">
                <FormOutlined />
              </n-icon>
              <span>编辑机构{{ treeItemTitle ? `：${treeItemTitle}` : '' }}</span>
            </n-space>
          </template>
          <n-alert type="info" closable> 从机构列表选择一项后，进行编辑</n-alert>
          <n-form
            :model="formParams"
            :rules="rules"
            ref="formRef"
            label-placement="left"
            :label-width="100"
            v-if="isEditMenu"
            class="py-4"
          >
            <n-form-item label="上级机构ID" path="parentId">
              <n-input-number :show-button="false" disabled v-model:value="formParams.parentId" />
            </n-form-item>
            <n-form-item label="名称" path="label">
              <n-input placeholder="请输入名称" v-model:value="formParams.label" />
            </n-form-item>
            <n-form-item label="联系方式" path="tel">
              <n-input placeholder="请输入联系方式" v-model:value="formParams.tel" />
            </n-form-item>
            <n-form-item label="状态" path="status">
              <n-radio-group v-model:value="formParams.status" name="status">
                <n-space>
                  <n-radio :value="1">启用</n-radio>
                  <n-radio :value="0">禁用</n-radio>
                </n-space>
              </n-radio-group>
            </n-form-item>
            <n-form-item label="排序" path="sequence">
              <n-input-number
                :show-button="false"
                placeholder="请输入排序"
                v-model:value="formParams.sequence"
              />
            </n-form-item>
            <n-form-item label="描述" path="description">
              <n-input
                type="textarea"
                placeholder="请输入描述"
                v-model:value="formParams.description"
              />
            </n-form-item>
            <n-form-item path="auth" style="margin-left: 100px">
              <n-space>
                <n-button type="primary" :loading="subLoading" @click="formSubmit"
                  >保存修改</n-button
                >
                <n-button type="warning" @click="handleReset">重置</n-button>
                <n-button type="error" @click="handleDel">删除</n-button>
              </n-space>
            </n-form-item>
          </n-form>
        </n-card>
      </n-gi>
    </n-grid>
    <CreateDrawer
      ref="createDrawerRef"
      @loadOrgTree="loadOrgTree"
      :title="drawerTitle"
      :parentId="treeItemParentId"
    />
  </fs-page>
</template>
<script lang="ts" setup>
  import { ref, unref, reactive, onMounted } from 'vue';
  import { useDialog, useMessage } from 'naive-ui';
  import { FileAddTwotone, AlignLeftOutlined, SearchOutlined, FormOutlined } from '@vicons/antd';
  import { getOrgList } from '@/api/system/org';
  import { getTreeItem } from '@/utils';
  import CreateDrawer from './CreateDrawer.vue';
  import { OrgListItem } from '@/api/system/model/systemModel';
  import { SaveOrUpdate, DelObj } from './api';

  const rules = {
    label: {
      required: true,
      message: '请输入名称',
      trigger: 'blur',
    },
  };

  const formRef: any = ref(null);
  const createDrawerRef = ref();
  const message = useMessage();
  const dialog = useDialog();

  let treeItemKey = ref([]);

  let expandedKeys = ref([]);

  const treeData = ref<OrgListItem[]>([]);

  const loading = ref(true);
  const subLoading = ref(false);
  const isEditMenu = ref(false);
  const treeItemTitle = ref('');
  const treeItemParentId = ref(0);
  const pattern = ref('');
  const drawerTitle = ref('');

  const formParams = reactive({
    id: null,
    parentId: null,
    name: null,
    value: null,
    label: null,
    tel: null,
    status: 1,
    description: null,
    sequence: null,
  });

  function openCreateDrawer() {
    if (treeItemKey.value.length > 0) {
      drawerTitle.value = `父级机构：${treeItemTitle.value}`;
      const { openDrawer } = createDrawerRef.value;
      openDrawer();
    } else {
      drawerTitle.value = `父级机构：顶级根机构`;
      const { openDrawer } = createDrawerRef.value;
      openDrawer();
    }
  }

  function selectedTree(keys) {
    if (keys.length) {
      const treeItem = getTreeItem(unref(treeData), keys[0]);
      treeItemKey.value = keys;
      treeItemTitle.value = treeItem.label;
      treeItemParentId.value = treeItem.id;
      Object.assign(formParams, treeItem);
      formParams.status = formParams.status ? 1 : 0;
      isEditMenu.value = true;
    } else {
      isEditMenu.value = false;
      treeItemKey.value = [];
      treeItemTitle.value = '';
      treeItemParentId.value = 0;
    }
  }

  function handleDel() {
    dialog.info({
      title: '提示',
      content: `您确定想删除此机构信息吗?`,
      positiveText: '确定',
      negativeText: '取消',
      onPositiveClick: () => {
        DelObj(formParams.id).then(() => {
          message.success('操作成功', { duration: 3 });
          selectedTree([]);
          loadOrgTree();
        });
      },
    });
  }

  function handleReset() {
    const treeItem = getTreeItem(unref(treeData), treeItemKey.value[0]);
    Object.assign(formParams, treeItem);
    formParams.status = formParams.status ? 1 : 0;
  }

  function formSubmit() {
    formRef.value.validate((errors: boolean) => {
      if (!errors) {
        SaveOrUpdate(formParams).then(() => {
          message.success('操作成功', { duration: 3 });
        });
      } else {
        message.error('请填写完整机构信息');
      }
    });
  }

  function packHandle() {
    if (expandedKeys.value.length) {
      expandedKeys.value = [];
    } else {
      expandedKeys.value = unref(treeData).map((item: any) => item.key as string) as [];
    }
  }

  async function loadOrgTree() {
    const treeMenuList = await getOrgList();
    if (treeMenuList) {
      const keys = treeMenuList.map((item) => item.id);
      Object.assign(formParams, keys);
      treeData.value = treeMenuList;
      expandedKeys.value = unref(treeData).map((item: any) => item.key as string) as [];
    }
    loading.value = false;
  }

  onMounted(async () => {
    await loadOrgTree();
  });

  function onExpandedKeys(keys) {
    expandedKeys.value = keys;
  }
</script>
